package com.example.homework4

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

import com.example.homework4.Model.CardMatching

class MainActivity : AppCompatActivity(), View.OnClickListener {

        private lateinit var game: CardMatching
        val cardButtons = mutableListOf<Button>()

        // 添加视图引用
        private lateinit var gridLayout: GridLayout
        private lateinit var score: TextView
        private lateinit var reset: Button

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            // 初始化视图
            gridLayout = findViewById(R.id.grid_layout)
            score = findViewById(R.id.text_score)
            reset = findViewById(R.id.btn_restart)

            // 收集所有按钮
            for (i in 0 until gridLayout.childCount) {
                val child = gridLayout.getChildAt(i)
                if (child is Button) {
                    child.setOnClickListener(this)
                    cardButtons.add(child)
                }
            }

            game = CardMatching(cardButtons.size)
            updateUI()

            reset.setOnClickListener {
                game = CardMatching(cardButtons.size)
                updateUI()
            }
        }

        private fun updateUI() {
            for (button in cardButtons) {
                val index = cardButtons.indexOf(button)
                val card = game.cardAtIndex(index)
                button.isEnabled = !card.isMatched
                if (card.isChosen) {
                    button.text = card.toString()
                    button.setBackgroundColor(Color.WHITE)
                } else {
                    button.text = ""
                    button.setBackgroundResource(R.drawable.dress)
                }
            }
            score.text = String.format("%s%d", "Score:", game.score)
        }

        override fun onClick(v: View?) {
            if (v is Button) {
                val index = cardButtons.indexOf(v)
                if (index != -1) {
                    game.chooseCardAtIndex(index)
                    updateUI()
                }
            }
        }
    }